package owl2vowl.parser.vowl;

import owl2vowl.model.data.VowlData;
import owl2vowl.model.entities.AbstractEntity;
import owl2vowl.model.entities.nodes.classes.VowlClass;
import owl2vowl.model.entities.nodes.classes.VowlThing;
import owl2vowl.model.entities.nodes.datatypes.VowlDatatype;
import owl2vowl.model.entities.nodes.datatypes.VowlLiteral;
import owl2vowl.model.entities.properties.TypeOfProperty;
import owl2vowl.model.entities.properties.VowlDatatypeProperty;
import owl2vowl.model.entities.properties.VowlObjectProperty;
import owl2vowl.model.individuals.VowlIndividual;
import owl2vowl.model.visitor.VowlElementVisitor;
import owl2vowl.parser.helper.ComparisonHelper;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Iterator;
import java.util.List;
import org.semanticweb.owlapi.model.IRI;

public class EquivalentSorter implements VowlElementVisitor {
	private IRI baseIri;
	private VowlData vowlData;

	public EquivalentSorter(IRI baseIri, VowlData vowlData) {
		this.baseIri = baseIri;
		this.vowlData = vowlData;
	}

	protected List<IRI> getSortedEquivalents(AbstractEntity entity) {
		ArrayList iriToSort = new ArrayList(entity.getEquivalentElements());
		Iterator arg2;
		IRI iri;
		if (ComparisonHelper.hasDifferentNameSpace(entity.getIri().toString(), this.baseIri.toString())) {
			arg2 = iriToSort.iterator();

			while (arg2.hasNext()) {
				iri = (IRI) arg2.next();
				if (!ComparisonHelper.hasDifferentNameSpace(iri.toString(), this.baseIri.toString())) {
					return Collections.emptyList();
				}
			}
		}

		arg2 = iriToSort.iterator();

		do {
			if (!arg2.hasNext()) {
				Collections.sort(iriToSort, (o1, o2) -> {
					return o1.equals(this.baseIri) ? 1 : 0;
				});
				return iriToSort;
			}

			iri = (IRI) arg2.next();
		} while (this.vowlData.getEntityForIri(iri).getEquivalentElements().size() <= iriToSort.size());

		return Collections.emptyList();
	}

	public void visit(VowlThing vowlThing) {
	}

	public void visit(VowlClass vowlClass) {
		if (vowlClass.getEquivalentElements().size() > 0) {
			vowlClass.setSortedEquivalents(this.getSortedEquivalents(vowlClass));
		}

	}

	public void visit(VowlLiteral vowlLiteral) {
	}

	public void visit(VowlDatatype vowlDatatype) {
		if (vowlDatatype.getEquivalentElements().size() > 0) {
			vowlDatatype.setSortedEquivalents(this.getSortedEquivalents(vowlDatatype));
		}

	}

	public void visit(VowlObjectProperty vowlObjectProperty) {
		if (vowlObjectProperty.getEquivalentElements().size() > 0) {
			vowlObjectProperty.setSortedEquivalents(this.getSortedEquivalents(vowlObjectProperty));
		}

	}

	public void visit(VowlDatatypeProperty vowlDatatypeProperty) {
		if (vowlDatatypeProperty.getEquivalentElements().size() > 0) {
			vowlDatatypeProperty.setSortedEquivalents(this.getSortedEquivalents(vowlDatatypeProperty));
		}

	}

	public void visit(TypeOfProperty typeOfProperty) {
	}

	public void visit(VowlIndividual vowlIndividual) {
	}
}